const cloud = require('wx-server-sdk');
const crypto = require('crypto');
cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
});
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext();

  switch (event.type) {
    case 'text':{
      return secText(event.msg);
    }
    break;
    case 'image':{
      return secImg(event.msg);
      }
    break;
    case 'video':{
      return secVideo(event.msg);
      }
    break;
    case 'file':{
      return secFile(event.msg);
      }
    break;
    case 'audio':{
      return secAudio(event.msg);
      }
    break;
  }

}
async function secText(e)
{
  try {
    let {OPENID}=cloud.getWXContext();
    const result = await cloud.openapi.security.msgSecCheck({
      "openid": OPENID,
      "scene": 4,
      "version": 2,
      "content": e
      })
    return result;
  } catch (err) {
    return err
  }
}
async function secImg(e)
{
  try {
    let result = await cloud.openapi.security.imgSecCheck({
      media: {
        contentType: 'image/png',
        value: Buffer.from(e,'base64')
      }
    })
    if (result && result.errCode.toString() === '87014') {
      return {
        errCode: 1,
        errMsg: '图片不合法',
      } 
    } else {
      return {
        errCode: 0,
        errMsg: 'ok',
      }
    }
  } 
  catch (err) {
    if (err.errCode.toString() === '87014') {
      return {
        errCode: 1,
        errMsg: '图片不合法',
      } 
    }
    return {
      errCode: 2,
      errMsg: '图片安检失败',
    }
  }
}
async function secVideo(e)
{
  try {
    const result = await cloud.openapi.security.msgSecCheck({
        "openid": OPENID,
        "scene": 4,
        "version": 2,
        "content": e
      })
    return result
  } catch (err) {
    return err
  }
}
async function secFile(e)
{
  try {
    const result = await cloud.openapi.security.msgSecCheck({
        "openid": OPENID,
        "scene": 4,
        "version": 2,
        "content": e
      })
    return result
  } catch (err) {
    return err
  }
}
async function secAudio(e)
{
  try {
    const result = await cloud.openapi.security.msgSecCheck({
        "openid": OPENID,
        "scene": 4,
        "version": 2,
        "content": e
      })
    return result
  } catch (err) {
    return err
  }
}